package com.pool.activity;

import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.pool.R;
import com.pool.activity.common.FullscreenListActivity;
import com.pool.common.Lists;
import com.pool.common.Maps;
import com.pool.common.Record;
import com.pool.common.Shoot;
import com.pool.common.Strings;
import com.pool.store.RecordStore;
import com.pool.store.ShootStore;
import com.pool.store.Store;

/**
 * Main activity, where the user can choose the player and sync/save to Spreadsheets.
 * 
 * @author claveld@gmail.com (David Clavel)
 */
public class SelectPlayer extends FullscreenListActivity {

  private static final String TAG = "SelectPlayer";
    
  private static final String TITLE = "title";
  private static final String INTENT = "intent";
  private static final String ACTION = "action";

  private static final int SELECT_SHOOT = 0;

  private enum Action {
    DEFAULT,
    SELECT_SHOOT,
    EXIT,
  }

  private final Store<Record> recordStore;
  private final Store<Shoot> shootStore;

  public SelectPlayer() {
    this(new RecordStore(), new ShootStore());
  }

  public SelectPlayer(Store<Record> recordStore, Store<Shoot> shootStore) {
    this.recordStore = recordStore;
    this.shootStore = shootStore;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    refreshList();
  }
  
  private void refreshList() {
    List<Map<String, Object>> items = Lists.newArrayList();
    addItem(items,
            getTitleForPlayer(Strings.getString(R.string.david)),
            SelectShoot.createIntentForPlayer(this, Strings.getString(R.string.david)),
            Action.SELECT_SHOOT);
    addItem(items,
            getTitleForPlayer(Strings.getString(R.string.mateusz)),
            SelectShoot.createIntentForPlayer(this, Strings.getString(R.string.mateusz)),
            Action.SELECT_SHOOT);

    Intent viewStore = new Intent(this, ViewLocalStore.class);
    addItem(items, Strings.getString(R.string.view_local_store), viewStore, Action.DEFAULT);

    Intent statistics = new Intent(this, Statistics.class);
    addItem(items, Strings.getString(R.string.stats), statistics, Action.DEFAULT);
    
    Intent synchronizeShoots = LoginAndRun.createFor(this, Synchronize.class);
    addItem(items, Strings.getString(R.string.synchronize), synchronizeShoots, Action.DEFAULT);

    addItem(items, Strings.getString(R.string.exit), null, Action.EXIT);
    
    setListAdapter(
            new SimpleAdapter(this,
                    items,
                    android.R.layout.simple_list_item_1,
                    new String[] { TITLE },
                    new int[] { android.R.id.text1 }));
  }

  private String getTitleForPlayer(String player) {
    if (recordStore.getCount() == 0) {
      return player;
    }
    int victories = 0;
    int points = 0;
    
      for (Record record : recordStore.getAll()) {
        if (player.equals(record.player)) {
          Shoot shoot = shootStore.get(record.shootId);
          if (shoot.isVictory()) {
            victories++;
          }
          points += shoot.bonus;
        }
      }

      return player + " (" + victories + " v. | " + points + " pts)";
  }
  
  private void addItem(List<Map<String, Object>> list, String name, Intent intent, Action action) {
    Map<String, Object> map = Maps.newHashMap();
    map.put(TITLE, name);
    map.put(INTENT, intent);
    map.put(ACTION, action);
    list.add(map);
  }

  //  private WakeLock wakeLock = null;
  //  
  //  @Override
  //  public void onWindowFocusChanged(boolean hasFocus) {
  //    if (hasFocus) {
  //      PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
  //      wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
  //      wakeLock.acquire();
  //    } else {
  //      wakeLock.release();
  //    }
  //  }

  @Override
  public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
      refreshList();
    }
  }
  
  @SuppressWarnings("unchecked")
  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    Map<String, Object> map = (Map<String, Object>) l.getItemAtPosition(position);
    Action action = (Action) map.get(ACTION);
    Intent intent = (Intent) map.get(INTENT);

    switch (action) {
      case SELECT_SHOOT:
        startActivityForResult(intent, SELECT_SHOOT);
        break;
      case DEFAULT:
        startActivity(intent);
        break;
      case EXIT:
        setResult(RESULT_OK, getIntent());
        finish();
        return;
      default:
        Log.w(TAG, "Unknown action '" + action.name());
        startActivityForResult(intent, -1);
        break;
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == SELECT_SHOOT) {
      if (resultCode == RESULT_OK) {
        String player = data.getExtras().getString(SelectShoot.PLAYER);
        String shootId = data.getExtras().getString("shoot");
        int remainingBalls = data.getExtras().getInt("balls");
        Shoot shoot = shootStore.get(shootId);
        
        saveShoot(player, shoot, remainingBalls);
      }
    }
  }

  private void saveShoot(String player, Shoot shoot, int remainingBalls) {
    recordStore.add(Record.of(player, shoot.id, remainingBalls));
    String notificationText = player + ": " + shoot.description + " (" + shoot.bonus + " pts)";
    if (shoot.isVictory()) {
      String plural = "";
      if (remainingBalls > 1) { plural = "s"; }
        notificationText += "\n" + remainingBalls + " ball" + plural + " remaining";
    }
    Toast.makeText(this, notificationText, Toast.LENGTH_SHORT).show();
  }
}
